package com.woniuxy.joylifeforum.controller;

import com.woniuxy.common.utils.JWTUtils;
import com.woniuxy.joylifeforum.service.NewsService;
import com.woniuxy.joylifeforum.utils.RedisUtil;
import lombok.Data;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@ServerEndpoint("/userChat")
@Data
public class ChatWebSocketController {
    public static ConcurrentHashMap<String,Session> sessions=new ConcurrentHashMap<>();
    public static ConcurrentHashMap<Session,String> userIds=new ConcurrentHashMap<>();
    //以此获取bean
    public static ApplicationContext applicationContext;
    //赋值
    public static void setApplicationContext(ApplicationContext applicationContext) {
        ChatWebSocketController.applicationContext = applicationContext;
    }
    //建立连接
    @OnOpen
    public void openSession() {
        System.out.println("用户登录websocket");
    }
    //回调消息
    @OnMessage
    public void onMessage(String message,Session session) {
        /*System.out.println("查询消息："+message);
        System.out.println(session.toString());*/
        RedisUtil redisUtil = (RedisUtil) applicationContext.getBean("redisUtil");

        if(message.startsWith("refreshtoken-")){
            String refreshtoken = message.substring(13,45);
            //System.out.println(refreshtoken);
            String oppositeUserId=message.substring(46);
            //System.out.println(oppositeUserId);
            //获取用户iD
            Map<Object, Object> hmget = redisUtil.hmget(refreshtoken);
            String userId = JWTUtils.getUserId(hmget.get("token").toString());
            //建立连接
            sessions.put(userId+"-"+oppositeUserId,session);
            userIds.put(session,userId+"-"+oppositeUserId);
            System.out.println(sessions);
            System.out.println(userIds);
        }else if(message.startsWith("call_back-")){
            //暂时websocket回调无法写数据库，暂时屏蔽，改用验证session是否存在判断已读
            /*String callId = message.substring(10);
            String charId = redisUtil.get(callId).toString();
            //标记已读
            NewsService newsService = (NewsService) applicationContext.getBean("newsServiceImpl");
            newsService.isread(charId);
            System.out.println(callId);*/
        }
    }
    //用户离开
    @OnClose
    public void OnClose(Session session) {
        String userOppositeId = userIds.get(session);
        //移除
        sessions.remove(userOppositeId);
        userIds.remove(session);
        /*System.out.println(sessions);
        System.out.println(userIds);
        System.out.println("关闭连接："+session);*/
    }
}
